package com.topisv.tms.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.AreaService;
import org.springside.modules.web.Servlets;

/**
 * 区域管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /area/ Create page : GET /area/create Create action : POST
 * /area/create Update page : GET /area/update/{id} Update action : POST
 * /area/update Delete action : GET /area/delete/{id}
 * 
 * @author Arthur
 */
@Controller
@RequestMapping(value = "/area")
public class AreaController {

	private static final int PAGE_SIZE = 100;

	private static final Logger logger = LoggerFactory.getLogger(AreaController.class);

	@Autowired
	private AreaService areaService;

	@Autowired
	private AreaGroupService areaGroupService;

	@RequestMapping(value = "show")
	public String list(
			@RequestParam(value = "sortType", defaultValue = "areaName_asc") String sortType,
			@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			Model model, ServletRequest request) {
		logger.info("get area list begin");
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				request, "search_");

		Page<Area> areas = areaService.getArea("1", searchParams, pageNumber,
				PAGE_SIZE, sortType);
		model.addAttribute("areas", areas);
		model.addAttribute("sortType", sortType);
		model.addAttribute("searchParams", Servlets
				.encodeParameterStringWithPrefix(searchParams, "search_"));
		logger.info("get area list end");
		return "area/areaList";
	}

	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String createForm(Model model) {
		List<AreaGroup> areaGroups = areaGroupService.findAll();
		model.addAttribute("areaGroups", areaGroups);
		List<Map> areas = areaService.getParentAreaTree();
		model.addAttribute("areas", areas);
		model.addAttribute("area", new Area());
		model.addAttribute("action", "create");
		return "area/areaForm";
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create(@Valid Area area, RedirectAttributes redirectAttributes) {
		try {
			AreaGroup areaGroup = areaGroupService.getAreaGroup(area
					.getAreagroupId());
			area.setAreaGroup(areaGroup);
			Area area2 = areaService.getArea(area.getParentId());
			area.setArea(area2);
			areaService.saveArea(area);
			redirectAttributes.addFlashAttribute("message", "创建区域成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/area/";
	}

	@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") Long id, Model model,
			RedirectAttributes redirectAttributes) {
		try {
			List<AreaGroup> areaGroup = areaGroupService.findAll();
			model.addAttribute("areaGroups", areaGroup);
			List<Map> areas = areaService.getParentAreaTree();
			model.addAttribute("areas", areas);
			model.addAttribute("area", areaService.getArea(id));
			model.addAttribute("action", "update");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "area/areaForm";
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("area") Area area,
			RedirectAttributes redirectAttributes) {
		try {
			AreaGroup areaGroup = areaGroupService.getAreaGroup(area
					.getAreagroupId());
			area.setAreaGroup(areaGroup);
			Area area2 = areaService.getArea(area.getParentId());
			area.setArea(area2);
			areaService.saveArea(area);
			redirectAttributes.addFlashAttribute("message", "更新区域成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/area/";
	}

	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id,
			RedirectAttributes redirectAttributes) {
		try {
			List<Area> subAreas = areaService.getSubAreasById(id);
			for (Area subArea : subAreas) {
				subArea.setArea(areaService.getArea(1L));
			}
			areaService.deleteArea(id);
			redirectAttributes.addFlashAttribute("message", "删除区域成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", e.getMessage());
		}
		return "redirect:/area/";
	}

	/**
	 * 使用@ModelAttribute, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
	 */
	@ModelAttribute("preloadArea")
	public Area getArea(@RequestParam(value = "id", required = false) Long id) {
		if (id != null) {
			return areaService.getArea(id);
		}
		return null;
	}

	/**
	 * 取出Shiro中的当前用户Id.
	 */
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
	}
}
